// 文章分类
const express = require('express');
const router = express.Router()
const { db, genid } = require('../db/DbConnect');

// 获取指定的一条数据
router.get('/detail', async (req, res) => {
    let { id } = req.query
    let detail_sql = `SELECT * FROM blog WHERE id =? `
    try {
        let detail_res = await db.async.all(detail_sql, [id])
        // console.log(detail_res);
        if (!detail_res.length) {
            throw new Error('搜索条件有误')
        } else {
            res.send({
                code: 200,
                msg: '数据获取成功',
                data: detail_res
            })
        }
    } catch (error) {
        res.send({
            code: 500,
            msg: '数据获取失败',
            err: error.message
        })
    }
})

// 获取
router.get('/list', async (req, res) => {
    // 获取传参
    let { category_id, keyword, page, pageSize } = req.query
    // console.log({ category_id, keyword, page, pageSize });
    page = page || 1
    pageSize = pageSize || 10
    category_id = category_id || 0
    keyword = keyword || ""

    let params = []
    let whereSqls = []
    if (category_id != 0) {
        whereSqls.push(`category_id =? `)
        params.push(category_id)
    }
    if (keyword != "") {
        whereSqls.push(`(title LIKE ? OR content LIKE ?) `)
        params.push(`%${keyword}%`)
        params.push(`%${keyword}%`)
    }
    let whereSqlStr = ""
    if (whereSqls.length > 0) {
        whereSqlStr = `WHERE ` + whereSqls.join(`AND `)
    }

    // 分页数据
    let searchSql = `SELECT id, category_id, title, substr(content, 0, 50) AS content, update_time FROM blog ` +
        whereSqlStr + `ORDER BY create_time DESC LIMIT ?,? `
    let searchSqlParams = params.concat([(page - 1) * pageSize, pageSize])
    // 数据总数
    let searchCountSql = `SELECT COUNT(*) AS count FROM blog ` + whereSqlStr
    let searchCountSqlParams = params

    try {
        let [searchRes, searchCountRes] = await Promise.all([
            await db.async.all(searchSql, searchSqlParams),
            await db.async.all(searchCountSql, searchCountSqlParams)
        ])
        if (searchRes.length > 0 && searchCountRes[0].count) {
            res.send({
                code: 200,
                msg: "搜索成功",
                count: searchCountRes[0].count,
                data: searchRes,
            })
        } else {
            throw new Error('搜索条件有误')
        }
    } catch (error) {
        res.send({
            code: 500,
            msg: "搜索失败",
            err: error.message
        })
    }
})

// 删除
router.post('/_token/delete', async (req, res) => {
    let { id } = req.body
    try {
        let delete_blog_sql = `
        DELETE FROM blog WHERE id =?`
        let _dbres = await db.async.run(delete_blog_sql, [id])

        res.status(200).send({
            code: 200,
            msg: '删除成功',
        })
    } catch (error) {
        res.status(500).send({
            code: 500,
            msg: '删除失败',
            error: error.message
        })
    }
})

// 修改
router.post('/_token/update', async (req, res) => {
    let { id, title, category_id, content } = req.body
    let update_time = new Date().getTime()
    try {
        let update_blog_sql = `
        UPDATE blog SET 
        title =?, category_id =?, content =?, update_time =? 
        WHERE id =?`
        let params = [title, category_id, content, update_time, id]
        let _dbres = await db.async.run(update_blog_sql, params)

        res.status(200).send({
            code: 200,
            msg: '修改成功',
        })
    } catch (error) {
        res.status(500).send({
            code: 500,
            msg: '修改失败',
            error: error.message
        })
    }
})

// 添加
router.post('/_token/add', async (req, res) => {
    let { title, category_id, content } = req.body
    category_id = category_id || 0
    let id = genid.NextId()
    let create_time = new Date().getTime()
    try {
        let insert_blog_sql = `
        INSERT INTO blog 
        (id, title, category_id, content, create_time, update_time) 
        VALUES (?, ?, ?, ?, ?, ?)`
        let params = [id, title, category_id, content, create_time, create_time]
        let _dbres = await db.async.run(insert_blog_sql, params)

        res.status(200).send({
            code: 200,
            msg: '添加成功',
        })
    } catch (error) {
        res.status(500).send({
            code: 500,
            msg: '添加失败',
            error: error.message
        })
    }
})

module.exports = router
